<?php
/**
 * I-Cafe framework
 * 
 * @category CF
 * @package CF_Db
 * @link http://www.i-cafe.org
 * @license http://www.i-cafe.org/license
 * @version 04-04-2010
 * @author tcl_java@yahoo.com
 */

class CF_Db_QueryPart
{
	/**
	 * 
	 * @param string|CF_Db_Expr $cond
	 * @param mixed $values [optional]
	 * @param boolean $or [optional]
	 * @return string
	 */
	protected static function _where($cond, $values = null, $or = false)
	{
		if(null == $cond) return;
		
		$res = ($or? 'OR ' : 'AND ');
		
		if($cond instanceof CF_Db_Expr)
			return $res . "($cond)";
		
		if(null === $values){
			$res .= "($cond)";
		}else{
			if(!is_array($values)) $values = array($values);
			$values = CF_Db::getInstance()->quote($values);
			$res .= vsprintf("($cond)", $values);
		}
		return $res;
	}
	
	/**
	 * 
	 * @param string|CF_Db_Expr $cond
	 * @param mixed $values [optional]
	 * @return string
	 */
	public static function where($cond, $values = null)
	{
		return self::_where($cond, $values);
	}
	
	/**
	 * 
	 * @param string|CF_Db_Expr $cond
	 * @param mixed $values [optional]
	 * @return string
	 */
	public static function orWhere($cond, $values = null)
	{
		return self::_where($cond, $values, true);
	}
	
	/**
	 * 
	 * @param string|array|CF_Db_Expr $columns
	 * @param string $direction [optional]
	 * @return string
	 */
	public static function order($columns, $direction = null)
	{
		if(null == $columns) return;
		
		if($columns instanceof CF_Db_Expr)
			return (string) $columns;
			
		if(!is_array($columns)){
			$columns = CF_Db::getInstance()->quoteIdentifier($columns);
			
			if($direction){
				$direction = strtoupper(trim($direction));
				if(in_array($direction, array('ASC', 'DESC')))
					$columns .= ' ' . $direction;
			}
			
			return $columns;
		}
		
		$res = array();
		foreach($columns as $direction => $col){
			$res[] = self::order($col, $direction);
		}
		
		return implode(',', $res);
	}
	
	/**
	 * 
	 * @param int $count
	 * @param int $offset [optional]
	 * @return string
	 */
	public static function limit($count, $offset = null)
	{
		if(null == $count) return;
		
		return "LIMIT $count" . ($offset? " OFFSET $offset" : '');
	}
}
